# common/MessageHandler.py

from common.DS18B20Sensor import DS18B20Sensor
import time

class MessageHandler:
    def __init__(self, mqtt_client):
        self.mqtt_client = mqtt_client
        self.message_handlers = {
            b'readTemp': self.handle_read_temp,
            b'command1': self.handle_command1,
            b'command2': self.handle_command2,
            # 可以添加更多的命令和处理函数
        }
        self.processed_messages = set()  # 用于存储已处理的消息

    def process_message(self):
        latest_message = self.mqtt_client.get_latest_message()
        # print(f"latest_message message: {latest_message}")
        if latest_message and latest_message not in self.processed_messages:
            topic, msg = latest_message
            print(f"Processing message: {msg} from topic: {topic}")
            
            # 提取消息中的方法名
            method_name, _ = self.extract_method_and_timestamp(msg)
            
            # 标记此消息为已处理
            self.processed_messages.add(latest_message)
            
            # 根据消息内容调用相应的处理函数
            handler = self.message_handlers.get(method_name)
            if handler:
                return handler(topic, msg)
            else:
                print(f"No handler found for message: {msg}")
        return None

    def extract_method_and_timestamp(self, msg):
        # 消息格式：方法名#时间戳
        parts = msg.split(b'#', 1)
        if len(parts) == 2:
            method_name, timestamp = parts
            return method_name, timestamp
        else:
            return None, None

    def handle_read_temp(self, topic, msg):
        print("Handling readTemp command")
        tempRead = DS18B20Sensor(13)
        temperature = tempRead.read_temperature()
        print(f"Current temperature: {temperature}°C")
        self.mqtt_client.publish(f"E32_P_Temperature: {temperature}°C")
        return f"Temperature read: {temperature}°C"

    def handle_command1(self, topic, msg):
        print("Handling command1")
        # 在这里添加处理 command1 的具体逻辑
        # 例如：控制某个设备、更新状态等
        return f"Command1 processed: {msg}"

    def handle_command2(self, topic, msg):
        print("Handling command2")
        # 在这里添加处理 command2 的具体逻辑
        # 例如：发送通知、记录日志等
        return f"Command2 processed: {msg}"